<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;

abstract class Controller
{
    /**
     * 返回成功的JSON响应
     */
    protected function success($data = null, string $message = '操作成功', int $status = 200): JsonResponse
    {
        return response()->json([
            'success' => true,
            'code' => $status,
            'message' => $message,
            'data' => $data,
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ], $status);
    }

    /**
     * 返回失败的JSON响应
     */
    protected function error(string $message = '操作失败', int $status = 400, $errors = null): JsonResponse
    {
        $response = [
            'success' => false,
            'code' => $status,
            'message' => $message,
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ];

        if ($errors) {
            $response['errors'] = $errors;
        }

        return response()->json($response, $status);
    }

    /**
     * 返回分页数据的JSON响应
     */
    protected function paginate(LengthAwarePaginator $paginator, string $message = '获取数据成功'): JsonResponse
    {
        return response()->json([
            'success' => true,
            'code' => 200,
            'message' => $message,
            'data' => $paginator->items(),
            'pagination' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
                'from' => $paginator->firstItem(),
                'to' => $paginator->lastItem(),
            ],
            'timestamp' => now()->toISOString(),
            'request_id' => uniqid()
        ]);
    }

    /**
     * 验证请求数据
     */
    protected function validateRequest($request, array $rules, array $messages = []): array
    {
        return $request->validate($rules, $messages);
    }
}
